import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Categories from '../components/goods/Categories.vue'
import Params from '../components/goods/Params.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'




Vue.use(VueRouter)


const routes = [
  {
    path: '/',
    redirect: '/login'    //路由重定向到 login 登录页面
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome,
      },
      {
        path: '/users',
        component: Users,
      },
      {
        path: '/rights',
        component: Rights,
      },
      {
        path: '/roles',
        component: Roles,
      },
      {
        path: '/categories',
        component: Categories,
      },
      {
        path: '/params',
        component: Params,
      },
      {
        path: '/goods',
        component: List,
      },
      {
        path: '/goods/add',
        component: Add,
      },
      {
        path: '/orders',
        component: Order,
      },
      {
        path: '/reports',
        component: Report,
      },
    ]
  }
]

const router = new VueRouter({
  routes
})



// 路由导航守卫：访问权限控制（若是用户没有登录，而直接通过 URL 进行页面的访问，则强制跳转到登录页面）
router.beforeEach((to, from, next) => {
  //如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  
  // 从 sessionStorage 中获取到 保存的 token 值
  const tokenStr = window.localStorage.getItem('token')

  // 没有 token 强制跳转到登录页
  if (!tokenStr) return next('/login')  
  next()
})





export default router



